<?php
/**
 * 采购入库单
 * Created by PhpStorm.
 * User: echa
 * Date: 2018/1/25
 * Time: 19:02
 *
 */

namespace App\Services\Warehouse;



use App\Repositories\Warehouse\WarehouseRepository;

class PurchaseRequisitionService extends PublicService {
    //采购入库表单ID
    //protected  $Formid='STK_InStock';

    protected $WarehouseRepository;
    public function __construct(WarehouseRepository $warehouseRepository)
    {
        parent::__construct(config('k3cloud.PurchaseRequisition'));
        $this->WarehouseRepository=$warehouseRepository;
    }


    /**
     * 查看
     * */
    public  function ViewPurchaseRequisition($Number='',$Id=''){
        return $this->view($Number,$Id);
    }

    /**
       保存
     * 1.formid：业务对象表单Id（必录）
        2.data：Json格式数据（详情参考Json格式数据）（必录）
        2.1.Creator：创建者名字（非必录）
        2.2.NeedUpDateFields：需要保存的字段,格式["fieldkey1","fieldkey2","entitykey1",...]，数组类型(非必录)
        2.3.NeedReturnFields：需要返回的结果字段,格式["fieldkey","entitykey.fieldkey",...]（非必录）
        2.4.IsDeleteEntry：是否删除分录，默认True删除（非必录）
        2.5.SubSystemId：菜单所在子系统Id（非必录）
        2.6.IsVerifyBaseDataField：是否验证所有的基础资料，默认False不验证（非必录）
        2.7.IsEntryBatchFill：是否批量填充分录：默认为Ture（非必录）
        2.8.Model：表单实体数据（必录）
     */
    public function SavePurchaseRequisition($arrdata=[]){
           if(empty($arrdata['FID'])){
               $arrdata['FID']="0";
           }
           if(empty($arrdata['FBillNo'])){
               $arrdata['FBillNo']="";
           }
           if(empty($arrdata['k3_number'])){
               $arrdata['k3_number']="";
           }
            $goods=$this->PostGoodsData($arrdata['GoodsData']);
            $data=[
                "FID"=>$arrdata['FID'],
                "FBillTypeID"=>[
                    "FNumber"=>"RKD01_SYS"
                ],
                "FBillNo"=>$arrdata['FBillNo'],
                "FDate"=>date('Y-m-d H:i:s',time()),
                "FStockOrgId"=>[
                    "FNumber"=>config('k3cloud.organization')
                ],
                "FStockDeptId"=>[
                    "FNumber"=>""
                ],
                "FStockerGroupId"=>[
                    "FNumber"=>""
                ],
                "FStockerId"=>[
                    "FNumber"=>""
                ],
                "FDemandOrgId"=>[
                    "FNumber"=>config('k3cloud.organization')
                ],
                "FCorrespondOrgId"=>[
                    "FNumber"=>config('k3cloud.organization')
                ],
                "FPurchaseOrgId"=>[
                    "FNumber"=>config('k3cloud.organization')
                ],
                "FPurchaseDeptId"=>[
                    "FNumber"=>""
                ],
                "FPurchaserGroupId"=>[
                    "FNumber"=>""
                ],
                "FPurchaserId"=>[
                    "FNumber"=>""
                ],
                "FSupplierId"=>[
                    "FNumber"=>$arrdata['k3_number']
                ],
                "FSupplyId"=>[
                    "FNumber"=>$arrdata['k3_number']
                ],
                "FSupplyAddress"=>"",
                "FSettleId"=>[
                    "FNumber"=>$arrdata['k3_number']
                ],
                "FChargeId"=>[
                    "FNumber"=>$arrdata['k3_number']
                ],
                "FOwnerTypeIdHead"=>"BD_OwnerOrg",
                "FOwnerIdHead"=>[
                    "FNumber"=>"100"
                ],
                "FConfirmerId"=>[
                    "FUserID"=>""
                ],
                "FConfirmDate"=>"1900-01-01",
                "FScanBox"=>"",
                "FCDateOffsetUnit"=>"",
                "FCDateOffsetValue"=>0,
                "FProviderContactID"=>[
                    "FCONTACTNUMBER"=>""
                ],
                "F_PAEZ_Base"=>[
                    "FNumber"=>""
                ],
                "FInStockFin"=>[
                    "FSettleOrgId"=>[
                        "FNumber"=>config('k3cloud.organization')
                    ],
                    "FSettleTypeId"=>[
                        "FNumber"=>""
                    ],
                    "FPayConditionId"=>[
                        "FNumber"=>""
                    ],
                    "FSettleCurrId"=>[
                        "FNumber"=>"PRE001"
                    ],
                    "FIsIncludedTax"=>true,
                    "FPriceTimePoint"=>"1",
                    "FPriceListId"=>[
                        "FNumber"=>"CGJM000064"
                    ],
                    "FDiscountListId"=>[
                        "FNumber"=>""
                    ],
                    "FLocalCurrId"=>[
                        "FNumber"=>"PRE001"
                    ],
                    "FExchangeTypeId"=>[
                        "FNumber"=>"HLTX01_SYS"
                    ],
                    "FExchangeRate"=>1.0,
                    "FISPRICEEXCLUDETAX"=>true
                ],
                "FInStockEntry"=>$goods
            ];
            return $this->save($data);

    }

    /**
       提交
     * 1.formid：业务对象表单Id（必录）
        2.data：Json格式数据（详情参考Json格式数据）（必录）
        2.1.CreateOrgId：创建者组织，字符串类型（非必录）
        2.2.Numbers：单据编号集合，格式["billNo1","billNo1",...]，数组类型（必录）
     */
    public function  SubmitPurchaseRequisition($Numbers=[]){
        return $this->submit($Numbers);
    }


    /**
     * 审核
     */
    public function AuditPurchaseRequisition($Numbers=[]){
        return $this->audit($Numbers);
    }

    /**
     *单据列表查询
     * 1.data：Json格式数据（详情参考Json格式数据）（必录）
        1.1.FormId：业务对象表单Id（必录）
        1.2.FieldKeys：字段keys，字符串类型用逗号分隔，比如"key1,key2..."（必录）
        1.3.FilterString：过滤（非必录）  FBillNo=''
        1.4.OrderString：排序字段（非必录）
        1.5.TopRowCount：总行数（非必录）
        1.6.StartRow：开始行（非必录）
        1.7.Limit：最大行数，不能超过2000（非必录）
     */
    public function ExecuteBillQueryPurchaseRequisition($FieldKeys='',$FilterString='',$OrderString='',$TopRowCount='0',$StartRow='0',$Limit='20'){
            if(empty($FieldKeys)){
                $FieldKeys='FBillNo,FDate,FSupplyId,FDocumentStatus';
            }
            return $this->ExecuteBillQuery($FieldKeys,$FilterString,$OrderString,$TopRowCount,$StartRow,$Limit);
    }


    private function PostGoodsData($GoodsData){
        if(!is_array($GoodsData)){
            return false;
        }
        $goods=array();
        foreach ($GoodsData as $k=>$v){
            $goods[]=[
                "FEntryID"=>null,
                "FRowType"=>"Standard",
                "FWWInType"=>"",
                "FMaterialId"=>[
                    "FNumber"=>$v['goods_sn']
                ],
                "FUnitID"=>[
                    "FNumber"=>$v['spec_unit'],
                ],
                "FParentMatId"=>[
                    "FNumber"=>""
                ],
                "FRealQty"=>$v['goods_number'],
                "FPriceUnitID"=>[
                    "FNumber"=>$v['spec_unit']
                ],
                "FPrice"=>0.0,
                "FTaxCombination"=>[
                    "FNumber"=>""
                ],
                "FLot"=>[
                    "FNumber"=>""
                ],
                "FStockId"=>[
                    "FNumber"=>$v['stock_number']
                ],
                "FDisPriceQty"=>0.0,
                "FStockStatusId"=>[
                    "FNumber"=>"KCZT01_SYS"
                ],
                "FMtoNo"=>null,
                "FGiveAway"=>false,
                "FNote"=>null,
                "FProduceDate"=>null,
                "FExtAuxUnitId"=>[
                    "FNumber"=>""
                ],
                "FExtAuxUnitQty"=>0.0,
                "FCheckInComing"=>false,
                "FProjectNo"=>null,
                "FSampleDamageQty"=>0.0,
                "FSampleDamageBaseQty"=>0.0,
                "FIsReceiveUpdateStock"=>false,
                "FInvoicedJoinQty"=>0.0,
                "FPriceBaseQty"=>$v['goods_number'],
                "FSetPriceUnitID"=>[
                    "FNumber"=>""
                ],
                "FRemainInStockUnitId"=>[
                    "FNumber"=>$v['spec_unit']
                ],
                "FBILLINGCLOSE"=>false,
                "FRemainInStockQty"=>$v['goods_number'],
                "FAPNotJoinQty"=>$v['goods_number'],
                "FRemainInStockBaseQty"=>$v['goods_number'],
                "FTaxPrice"=>0.0,
                "FEntryTaxRate"=>17.00,
                "FDiscountRate"=>0.0,
                "FCostPrice"=>0.0,
                "FBOMId"=>[
                    "FNumber"=>""
                ],
                "FSupplierLot"=>null,
                "FExpiryDate"=>null,
                "FAuxUnitQty"=>0.0,
                "FBeforeDisPriceQty"=>0.0
            ];
        }
        return $goods;
    }

    /**
        采购入库单列表
     * 参数说明
     * $StartRow 开始行
     * $OrderString 排序字段
     * $Limit 最大行数，不能超过2000
     * 字段说明
     * FBillNo 单据编号
     * FSupplyId.FName  供应商
     * FCreateDate  创建时间
     * FDocumentStatus  单据状态 A-创建 B-审核中 C-已审核 D-重新审核 Z-暂存
     * F_PAEZ_Qty 商品种类
     * F_PAEZ_Qty1 商品实收总数
     * F_PAEZ_Text 创建人
     * FOwnerTypeIdHead 货主类型  FOwnerTypeBDOwnerOrg-非代销  FOwnerTypeBDSupplier-代销
     */
    public function ListPurchaseRequisition($wid,$StartRow=0,$OrderString,$Limit=20){
        if(empty($wid)){
            return false;
        }
        $winfo=$this->WarehouseRepository->GetWarehouseInfo($wid);
        if(empty($winfo['k3_number'])){
            return false;
        }
        //主仓库编号
        $k3_number=$winfo['k3_number'];
        $FieldKeys='FBillNo,FSupplyId.FName,FCreateDate,FDocumentStatus,F_PAEZ_Qty,F_PAEZ_Qty1,F_PAEZ_Text,FOwnerTypeIdHead';
        $FilterString="F_PAEZ_Base.Number='".$k3_number."'";
        if(empty($OrderString)){
            $OrderString='FCreateDate desc,FDocumentStatus asc';
        }
        $list=$this->ExecuteBillQuery($FieldKeys,$FilterString,$OrderString,0,$StartRow,$Limit);
        if($list){
            return $list;
        }else{
            return false;
        }
    }

    /**
        采购入库单详情
     * 参数说明
     * $FBillNo  单据编号
     * 字段说明
     * FBillNo 单据编号
     * FSupplyId.FName  供应商
     * FDocumentStatus  单据状态  A-创建 B-审核中 C-已审核 D-重新审核 Z-暂存
     * FMaterialId 物料编号
     * FMaterialName 物料名称
     * FRealQty 实收数量
     * FUnitID.FName 库存单位
     * FSRCBillNo 来源单号
     * F_PAEZ_Qty 总单据商品种类
     * F_PAEZ_Qty1 总单据商品实收总数
     * FOwnerTypeIdHead 货主类型  FOwnerTypeBDOwnerOrg-非代销  FOwnerTypeBDSupplier-代销
     */
    public function DetailsPurchaseRequisition($FBillNo=''){
        $FieldKeys='FBillNo,FSupplyId.FName,FDocumentStatus,FMaterialId,FMaterialName,FRealQty,FUnitID.FName,FSRCBillNo,F_PAEZ_Qty,F_PAEZ_Qty1,FOwnerTypeIdHead';
        $FilterString="FBillNo='".$FBillNo."'";
        return $this->ExecuteBillQuery($FieldKeys,$FilterString);
    }



}